Jupyter at Bryn Mawr College |
|||
Public notebooks: /services/public/dblank / jupyter.cs / Examples |
This notebook explores making a cell magic for nim.
First, we load libs that we will need for defining an IPython magic:
from IPython.core.magic import register_line_cell_magic
Now, we construct a file that contains nim code:
%%file default.nim
# This is a comment
echo("What's your name? ")
var name: string = "Kevin"
echo("Hi, ", name, "!")
Can we run the file and view the results?
import subprocess
import sys
p = subprocess.Popen(["nim", "compile", "--run", "default.nim"], stdout=subprocess.PIPE)
out, err = p.communicate()
if err:
print(err.decode("utf-8"), file=sys.stderr)
if out:
print(out.decode("utf-8"))
Now, we put that together into a cell magic:
@register_line_cell_magic
def nim(line, cell):
fp = open("default.nim", "w")
fp.write(cell)
fp.close()
p = subprocess.Popen(["nim", "compile", "--run", "default.nim"], stdout=subprocess.PIPE)
out, err = p.communicate()
if err:
print(err.decode("utf-8"), file=sys.stderr)
if out:
print(out.decode("utf-8"))
And now test it out:
%%nim
type Animal = ref object of RootObj
name: string
age: int
method vocalize(this: Animal): string = "..."
method ageHumanYrs(this: Animal): int = this.age
type Dog = ref object of Animal
method vocalize(this: Dog): string = "woof"
method ageHumanYrs(this: Dog): int = this.age * 7
type Cat = ref object of Animal
method vocalize(this: Cat): string = "meow"
var animals: seq[Animal] = @[]
animals.add(Dog(name: "Sparky", age: 10))
animals.add(Cat(name: "Mitten", age: 10))
for a in animals:
echo a.vocalize()
echo a.ageHumanYrs()